# coding: utf-8
# @Author: 莫小鱼
import os

from openpyxl import load_workbook
from openpyxl.utils.exceptions import InvalidFileException

from AutoWebTest.utils.log_util import logs


class ExcelRead:
    """
    读取excel文件数据
    """

    def __init__(self, file_path):
        self.file_path = file_path
        abspath = os.path.abspath(self.file_path)

        if not os.path.isfile(abspath):
            raise FileNotFoundError(f"文件路径不存在：{abspath}")

        self.workbook = load_workbook(self.file_path, read_only=False)

    def read_row(self, sheet_name='Sheet1', row_index=1):
        """
        读取excel文件一整行数据
        :param sheet_name: sheet页名
        :param row_index: 返回哪一行数据，索引从1开始
        :return:
        """
        sheet = self.workbook[sheet_name]
        rows_data = [cell.value for cell in sheet[row_index]]
        return rows_data

    def read_all_rows(self, sheet_name='Sheet1'):
        """
        读取全部行的数据
        :param sheet_name:sheet页名
        :return: 返回list,如：[['xx','xx'],['xx','xx'],['xx','xx']...]
        """
        try:
            all_rows_data = []
            sheet = self.workbook[sheet_name]
            max_col = sheet.max_column  # 获取excel最大的列数
            for row in sheet.iter_rows(min_row=1, max_row=sheet.max_row, min_col=1, max_col=max_col):
                row_data = [cell.value for cell in row]
                all_rows_data.append(row_data)
            return all_rows_data
        except Exception as e:
            logs.error(f"Excel文件读取异常：原因{e}")
        finally:
            self.close()

    def read_column(self, sheet_name='Sheet1', column_index=1):
        """
        获取一整列的数据
        :param sheet_name:sheet名称
        :param column_index: 返回哪一列的数据，索引从1开始
        :return:
        """
        try:
            columns_data = []
            sheet = self.workbook[sheet_name]
            for row in sheet.iter_rows(min_row=1, min_col=column_index, max_col=column_index):
                columns_data.append(row[0].value)
            return columns_data
        except Exception as e:
            logs.error(f"读取整列Excel数据异常：原因{e}")
        finally:
            self.close()

    def read_cell_value(self, row_index, column_index, sheet_name='Sheet1'):
        """
        获取单元格的数据
        :param sheet_name: sheet名
        :param row_index: 行索引
        :param column_index: 列索引
        :return:
        """
        try:
            sheet = self.workbook[sheet_name]
            return sheet.cell(row=row_index, column=column_index).value
        except Exception as e:
            logs.error(f"获取单元格数据异常：原因{e}")
        finally:
            self.close()

    def close(self):
        self.workbook.close()


# if __name__ == '__main__':
#     excel = ExcelRead('../../data/login.xlsx')
#     print(excel.read_all_rows())
